package me.fung.wubi.worker.printer

import me.fung.wubi.base.define.table.CodeTable
import me.fung.wubi.base.io.charsetMap
import java.io.File
import java.io.FileOutputStream

abstract class BaseTablePrinter : TablePrinter {

    abstract var outPutFile: File

    override fun print(table: CodeTable, config: PrintConfig) {
        val content = buildContent(table, config)
        output(content, config)
    }

    protected abstract fun buildContent(table: CodeTable, config: PrintConfig): String

    protected open fun output(content: String, config: PrintConfig) {
        FileOutputStream(outPutFile, false).buffered(1024 * 1024).use { outputStream ->
            if (config.sign) {
                val f = charsetMap.firstNotNullOfOrNull {
                    if (it.value == config.charset) it.key else null
                }
                f?.also {
                    outputStream.write(it)
                }
            }
            outputStream.write(content.toByteArray(config.charset))
        }
    }
}